232bd38208ef6bb694fe3b5e58b1ec06d0d554da
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28
29 /**
30 * Database abstraction object
31 * @ingroup Database
32 */
33 abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX = 1500000;
40
41 /** How long before it is worth doing a dummy query to test the connection */
42 const PING_TTL = 1.0;
43 const PING_QUERY = 'SELECT 1 AS ping';
44
45 const TINY_WRITE_SEC = .010;
46 const SLOW_WRITE_SEC = .500;
47 const SMALL_WRITE_ROWS = 100;
48
49 /** @var string SQL query */
50 protected $mLastQuery = '';
51 /** @var bool */
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
55 /** @var string */
56 protected $mServer;
57 /** @var string */
58 protected $mUser;
59 /** @var string */
60 protected $mPassword;
61 /** @var string */
62 protected $mDBname;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
66 protected $cliMode;
67 /** @var string Agent name for query profiling */
68 protected $agent;
69
70 /** @var BagOStuff APC cache */
71 protected $srvCache;
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
78
79 /** @var resource Database connection */
80 protected $mConn = null;
81 /** @var bool */
82 protected $mOpened = false;
83
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var array[] Map of (name => (callable, method name)) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
94
95 /** @var string */
96 protected $mTablePrefix;
97 /** @var string */
98 protected $mSchema;
99 /** @var integer */
100 protected $mFlags;
101 /** @var array */
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
107 /** @var array */
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
113 /** @var string */
114 protected $delimiter = ';';
115
116 /**
117 * Either 1 if a transaction is active or 0 otherwise.
118 * The other Trx fields may not be meaningfull if this is 0.
119 *
120 * @var int
121 */
122 protected $mTrxLevel = 0;
123 /**
124 * Either a short hexidecimal string if a transaction is active or ""
125 *
126 * @var string
127 * @see DatabaseBase::mTrxLevel
128 */
129 protected $mTrxShortId = '';
130 /**
131 * The UNIX time that the transaction started. Callers can assume that if
132 * snapshot isolation is used, then the data is *at least* up to date to that
133 * point (possibly more up-to-date since the first SELECT defines the snapshot).
134 *
135 * @var float|null
136 * @see DatabaseBase::mTrxLevel
137 */
138 private $mTrxTimestamp = null;
139 /** @var float Lag estimate at the time of BEGIN */
140 private $mTrxReplicaLag = null;
141 /**
142 * Remembers the function name given for starting the most recent transaction via begin().
143 * Used to provide additional context for error reporting.
144 *
145 * @var string
146 * @see DatabaseBase::mTrxLevel
147 */
148 private $mTrxFname = null;
149 /**
150 * Record if possible write queries were done in the last transaction started
151 *
152 * @var bool
153 * @see DatabaseBase::mTrxLevel
154 */
155 private $mTrxDoneWrites = false;
156 /**
157 * Record if the current transaction was started implicitly due to DBO_TRX being set.
158 *
159 * @var bool
160 * @see DatabaseBase::mTrxLevel
161 */
162 private $mTrxAutomatic = false;
163 /**
164 * Array of levels of atomicity within transactions
165 *
166 * @var array
167 */
168 private $mTrxAtomicLevels = [];
169 /**
170 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
171 *
172 * @var bool
173 */
174 private $mTrxAutomaticAtomic = false;
175 /**
176 * Track the write query callers of the current transaction
177 *
178 * @var string[]
179 */
180 private $mTrxWriteCallers = [];
181 /**
182 * @var float Seconds spent in write queries for the current transaction
183 */
184 private $mTrxWriteDuration = 0.0;
185 /**
186 * @var integer Number of write queries for the current transaction
187 */
188 private $mTrxWriteQueryCount = 0;
189 /**
190 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
191 */
192 private $mTrxWriteAdjDuration = 0.0;
193 /**
194 * @var integer Number of write queries counted in mTrxWriteAdjDuration
195 */
196 private $mTrxWriteAdjQueryCount = 0;
197 /**
198 * @var float RTT time estimate
199 */
200 private $mRTTEstimate = 0.0;
201
202 /** @var array Map of (name => 1) for locks obtained via lock() */
203 private $mNamedLocksHeld = [];
204
205 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
206 private $lazyMasterHandle;
207
208 /**
209 * @since 1.21
210 * @var resource File handle for upgrade
211 */
212 protected $fileHandle = null;
213
214 /**
215 * @since 1.22
216 * @var string[] Process cache of VIEWs names in the database
217 */
218 protected $allViews = null;
219
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
222
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
225
226 /** @var Profiler */
227 protected $profiler;
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
230
231 /**
232 * Constructor.
233 *
234 * FIXME: It is possible to construct a Database object with no associated
235 * connection object, by specifying no parameters to __construct(). This
236 * feature is deprecated and should be removed.
237 *
238 * IDatabase classes should not be constructed directly in external
239 * code. DatabaseBase::factory() should be used instead.
240 *
241 * @param array $params Parameters passed from DatabaseBase::factory()
242 */
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
248 $flags = $params['flags'];
249
250 $this->mSchema = $params['schema'];
251 $this->mTablePrefix = $params['tablePrefix'];
252
253 $this->cliMode = isset( $params['cliMode'] )
254 ? $params['cliMode']
255 : ( PHP_SAPI === 'cli' );
256 $this->agent = isset( $params['agent'] )
257 ? str_replace( '/', '-', $params['agent'] ) // escape for comment
258 : '';
259
260 $this->mFlags = $flags;
261 if ( $this->mFlags & DBO_DEFAULT ) {
262 if ( $this->cliMode ) {
263 $this->mFlags &= ~DBO_TRX;
264 } else {
265 $this->mFlags |= DBO_TRX;
266 }
267 }
268
269 $this->mSessionVars = $params['variables'];
270
271 $this->srvCache = isset( $params['srvCache'] )
272 ? $params['srvCache']
273 : new HashBagOStuff();
274
275 $this->profiler = isset( $params['profiler'] )
276 ? $params['profiler']
277 : Profiler::instance(); // @TODO: remove global state
278 $this->trxProfiler = isset( $params['trxProfiler'] )
279 ? $params['trxProfiler']
280 : new TransactionProfiler();
281 $this->connLogger = isset( $params['connLogger'] )
282 ? $params['connLogger']
283 : new \Psr\Log\NullLogger();
284 $this->queryLogger = isset( $params['queryLogger'] )
285 ? $params['queryLogger']
286 : new \Psr\Log\NullLogger();
287
288 if ( $user ) {
289 $this->open( $server, $user, $password, $dbName );
290 }
291 }
292
293 /**
294 * Given a DB type, construct the name of the appropriate child class of
295 * IDatabase. This is designed to replace all of the manual stuff like:
296 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
297 * as well as validate against the canonical list of DB types we have
298 *
299 * This factory function is mostly useful for when you need to connect to a
300 * database other than the MediaWiki default (such as for external auth,
301 * an extension, et cetera). Do not use this to connect to the MediaWiki
302 * database. Example uses in core:
303 * @see LoadBalancer::reallyOpenConnection()
304 * @see ForeignDBRepo::getMasterDB()
305 * @see WebInstallerDBConnect::execute()
306 *
307 * @since 1.18
308 *
309 * @param string $dbType A possible DB type
310 * @param array $p An array of options to pass to the constructor.
311 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
312 * @return IDatabase|null If the database driver or extension cannot be found
313 * @throws InvalidArgumentException If the database driver or extension cannot be found
314 */
315 final public static function factory( $dbType, $p = [] ) {
316 $canonicalDBTypes = [
317 'mysql' => [ 'mysqli', 'mysql' ],
318 'postgres' => [],
319 'sqlite' => [],
320 'oracle' => [],
321 'mssql' => [],
322 ];
323
324 $driver = false;
325 $dbType = strtolower( $dbType );
326 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
327 $possibleDrivers = $canonicalDBTypes[$dbType];
328 if ( !empty( $p['driver'] ) ) {
329 if ( in_array( $p['driver'], $possibleDrivers ) ) {
330 $driver = $p['driver'];
331 } else {
332 throw new InvalidArgumentException( __METHOD__ .
333 " type '$dbType' does not support driver '{$p['driver']}'" );
334 }
335 } else {
336 foreach ( $possibleDrivers as $posDriver ) {
337 if ( extension_loaded( $posDriver ) ) {
338 $driver = $posDriver;
339 break;
340 }
341 }
342 }
343 } else {
344 $driver = $dbType;
345 }
346 if ( $driver === false ) {
347 throw new InvalidArgumentException( __METHOD__ .
348 " no viable database extension found for type '$dbType'" );
349 }
350
351 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
352 // and everything else doesn't use a schema (e.g. null)
353 // Although postgres and oracle support schemas, we don't use them (yet)
354 // to maintain backwards compatibility
355 $defaultSchemas = [
356 'mssql' => 'get from global',
357 ];
358
359 $class = 'Database' . ucfirst( $driver );
360 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
361 // Resolve some defaults for b/c
362 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
363 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
364 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
365 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
366 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
367 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
368 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
369 if ( !isset( $p['schema'] ) ) {
370 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
371 }
372 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
373
374 $conn = new $class( $p );
375 if ( isset( $p['connLogger'] ) ) {
376 $conn->connLogger = $p['connLogger'];
377 }
378 if ( isset( $p['queryLogger'] ) ) {
379 $conn->queryLogger = $p['queryLogger'];
380 }
381 if ( isset( $p['errorLogger'] ) ) {
382 $conn->errorLogger = $p['errorLogger'];
383 } else {
384 $conn->errorLogger = function ( Exception $e ) {
385 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING );
386 };
387 }
388 } else {
389 $conn = null;
390 }
391
392 return $conn;
393 }
394
395 public function setLogger( LoggerInterface $logger ) {
396 $this->queryLogger = $logger;
397 }
398
399 public function getServerInfo() {
400 return $this->getServerVersion();
401 }
402
403 /**
404 * @return string Command delimiter used by this database engine
405 */
406 public function getDelimiter() {
407 return $this->delimiter;
408 }
409
410 /**
411 * Boolean, controls output of large amounts of debug information.
412 * @param bool|null $debug
413 * - true to enable debugging
414 * - false to disable debugging
415 * - omitted or null to do nothing
416 *
417 * @return bool|null Previous value of the flag
418 */
419 public function debug( $debug = null ) {
420 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
421 }
422
423 public function bufferResults( $buffer = null ) {
424 if ( is_null( $buffer ) ) {
425 return !(bool)( $this->mFlags & DBO_NOBUFFER );
426 } else {
427 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
428 }
429 }
430
431 /**
432 * Turns on (false) or off (true) the automatic generation and sending
433 * of a "we're sorry, but there has been a database error" page on
434 * database errors. Default is on (false). When turned off, the
435 * code should use lastErrno() and lastError() to handle the
436 * situation as appropriate.
437 *
438 * Do not use this function outside of the Database classes.
439 *
440 * @param null|bool $ignoreErrors
441 * @return bool The previous value of the flag.
442 */
443 protected function ignoreErrors( $ignoreErrors = null ) {
444 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
445 }
446
447 public function trxLevel() {
448 return $this->mTrxLevel;
449 }
450
451 public function trxTimestamp() {
452 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
453 }
454
455 public function tablePrefix( $prefix = null ) {
456 return wfSetVar( $this->mTablePrefix, $prefix );
457 }
458
459 public function dbSchema( $schema = null ) {
460 return wfSetVar( $this->mSchema, $schema );
461 }
462
463 /**
464 * Set the filehandle to copy write statements to.
465 *
466 * @param resource $fh File handle
467 */
468 public function setFileHandle( $fh ) {
469 $this->fileHandle = $fh;
470 }
471
472 public function getLBInfo( $name = null ) {
473 if ( is_null( $name ) ) {
474 return $this->mLBInfo;
475 } else {
476 if ( array_key_exists( $name, $this->mLBInfo ) ) {
477 return $this->mLBInfo[$name];
478 } else {
479 return null;
480 }
481 }
482 }
483
484 public function setLBInfo( $name, $value = null ) {
485 if ( is_null( $value ) ) {
486 $this->mLBInfo = $name;
487 } else {
488 $this->mLBInfo[$name] = $value;
489 }
490 }
491
492 public function setLazyMasterHandle( IDatabase $conn ) {
493 $this->lazyMasterHandle = $conn;
494 }
495
496 /**
497 * @return IDatabase|null
498 * @see setLazyMasterHandle()
499 * @since 1.27
500 */
501 public function getLazyMasterHandle() {
502 return $this->lazyMasterHandle;
503 }
504
505 /**
506 * @param TransactionProfiler $profiler
507 * @since 1.27
508 */
509 public function setTransactionProfiler( TransactionProfiler $profiler ) {
510 $this->trxProfiler = $profiler;
511 }
512
513 /**
514 * Returns true if this database supports (and uses) cascading deletes
515 *
516 * @return bool
517 */
518 public function cascadingDeletes() {
519 return false;
520 }
521
522 /**
523 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
524 *
525 * @return bool
526 */
527 public function cleanupTriggers() {
528 return false;
529 }
530
531 /**
532 * Returns true if this database is strict about what can be put into an IP field.
533 * Specifically, it uses a NULL value instead of an empty string.
534 *
535 * @return bool
536 */
537 public function strictIPs() {
538 return false;
539 }
540
541 /**
542 * Returns true if this database uses timestamps rather than integers
543 *
544 * @return bool
545 */
546 public function realTimestamps() {
547 return false;
548 }
549
550 public function implicitGroupby() {
551 return true;
552 }
553
554 public function implicitOrderby() {
555 return true;
556 }
557
558 /**
559 * Returns true if this database can do a native search on IP columns
560 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
561 *
562 * @return bool
563 */
564 public function searchableIPs() {
565 return false;
566 }
567
568 /**
569 * Returns true if this database can use functional indexes
570 *
571 * @return bool
572 */
573 public function functionalIndexes() {
574 return false;
575 }
576
577 public function lastQuery() {
578 return $this->mLastQuery;
579 }
580
581 public function doneWrites() {
582 return (bool)$this->mDoneWrites;
583 }
584
585 public function lastDoneWrites() {
586 return $this->mDoneWrites ?: false;
587 }
588
589 public function writesPending() {
590 return $this->mTrxLevel && $this->mTrxDoneWrites;
591 }
592
593 public function writesOrCallbacksPending() {
594 return $this->mTrxLevel && (
595 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
596 );
597 }
598
599 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
600 if ( !$this->mTrxLevel ) {
601 return false;
602 } elseif ( !$this->mTrxDoneWrites ) {
603 return 0.0;
604 }
605
606 switch ( $type ) {
607 case self::ESTIMATE_DB_APPLY:
608 $this->ping( $rtt );
609 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
610 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
611 // For omitted queries, make them count as something at least
612 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
613 $applyTime += self::TINY_WRITE_SEC * $omitted;
614
615 return $applyTime;
616 default: // everything
617 return $this->mTrxWriteDuration;
618 }
619 }
620
621 public function pendingWriteCallers() {
622 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
623 }
624
625 public function isOpen() {
626 return $this->mOpened;
627 }
628
629 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
630 if ( $remember === self::REMEMBER_PRIOR ) {
631 array_push( $this->priorFlags, $this->mFlags );
632 }
633 $this->mFlags |= $flag;
634 }
635
636 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
637 if ( $remember === self::REMEMBER_PRIOR ) {
638 array_push( $this->priorFlags, $this->mFlags );
639 }
640 $this->mFlags &= ~$flag;
641 }
642
643 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
644 if ( !$this->priorFlags ) {
645 return;
646 }
647
648 if ( $state === self::RESTORE_INITIAL ) {
649 $this->mFlags = reset( $this->priorFlags );
650 $this->priorFlags = [];
651 } else {
652 $this->mFlags = array_pop( $this->priorFlags );
653 }
654 }
655
656 public function getFlag( $flag ) {
657 return !!( $this->mFlags & $flag );
658 }
659
660 public function getProperty( $name ) {
661 return $this->$name;
662 }
663
664 public function getWikiID() {
665 if ( $this->mTablePrefix ) {
666 return "{$this->mDBname}-{$this->mTablePrefix}";
667 } else {
668 return $this->mDBname;
669 }
670 }
671
672 /**
673 * Get information about an index into an object
674 * @param string $table Table name
675 * @param string $index Index name
676 * @param string $fname Calling function name
677 * @return mixed Database-specific index description class or false if the index does not exist
678 */
679 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
680
681 /**
682 * Wrapper for addslashes()
683 *
684 * @param string $s String to be slashed.
685 * @return string Slashed string.
686 */
687 abstract function strencode( $s );
688
689 /**
690 * Called by serialize. Throw an exception when DB connection is serialized.
691 * This causes problems on some database engines because the connection is
692 * not restored on unserialize.
693 */
694 public function __sleep() {
695 throw new RuntimeException( 'Database serialization may cause problems, since ' .
696 'the connection is not restored on wakeup.' );
697 }
698
699 protected function installErrorHandler() {
700 $this->mPHPError = false;
701 $this->htmlErrors = ini_set( 'html_errors', '0' );
702 set_error_handler( [ $this, 'connectionerrorLogger' ] );
703 }
704
705 /**
706 * @return bool|string
707 */
708 protected function restoreErrorHandler() {
709 restore_error_handler();
710 if ( $this->htmlErrors !== false ) {
711 ini_set( 'html_errors', $this->htmlErrors );
712 }
713 if ( $this->mPHPError ) {
714 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
715 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
716
717 return $error;
718 } else {
719 return false;
720 }
721 }
722
723 /**
724 * @param int $errno
725 * @param string $errstr
726 */
727 public function connectionerrorLogger( $errno, $errstr ) {
728 $this->mPHPError = $errstr;
729 }
730
731 /**
732 * Create a log context to pass to PSR logging functions.
733 *
734 * @param array $extras Additional data to add to context
735 * @return array
736 */
737 protected function getLogContext( array $extras = [] ) {
738 return array_merge(
739 [
740 'db_server' => $this->mServer,
741 'db_name' => $this->mDBname,
742 'db_user' => $this->mUser,
743 ],
744 $extras
745 );
746 }
747
748 public function close() {
749 if ( $this->mConn ) {
750 if ( $this->trxLevel() ) {
751 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
752 }
753
754 $closed = $this->closeConnection();
755 $this->mConn = false;
756 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
757 throw new RuntimeException( "Transaction callbacks still pending." );
758 } else {
759 $closed = true;
760 }
761 $this->mOpened = false;
762
763 return $closed;
764 }
765
766 /**
767 * Make sure isOpen() returns true as a sanity check
768 *
769 * @throws DBUnexpectedError
770 */
771 protected function assertOpen() {
772 if ( !$this->isOpen() ) {
773 throw new DBUnexpectedError( $this, "DB connection was already closed." );
774 }
775 }
776
777 /**
778 * Closes underlying database connection
779 * @since 1.20
780 * @return bool Whether connection was closed successfully
781 */
782 abstract protected function closeConnection();
783
784 function reportConnectionError( $error = 'Unknown error' ) {
785 $myError = $this->lastError();
786 if ( $myError ) {
787 $error = $myError;
788 }
789
790 # New method
791 throw new DBConnectionError( $this, $error );
792 }
793
794 /**
795 * The DBMS-dependent part of query()
796 *
797 * @param string $sql SQL query.
798 * @return ResultWrapper|bool Result object to feed to fetchObject,
799 * fetchRow, ...; or false on failure
800 */
801 abstract protected function doQuery( $sql );
802
803 /**
804 * Determine whether a query writes to the DB.
805 * Should return true if unsure.
806 *
807 * @param string $sql
808 * @return bool
809 */
810 protected function isWriteQuery( $sql ) {
811 return !preg_match(
812 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
813 }
814
815 /**
816 * @param $sql
817 * @return string|null
818 */
819 protected function getQueryVerb( $sql ) {
820 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
821 }
822
823 /**
824 * Determine whether a SQL statement is sensitive to isolation level.
825 * A SQL statement is considered transactable if its result could vary
826 * depending on the transaction isolation level. Operational commands
827 * such as 'SET' and 'SHOW' are not considered to be transactable.
828 *
829 * @param string $sql
830 * @return bool
831 */
832 protected function isTransactableQuery( $sql ) {
833 $verb = $this->getQueryVerb( $sql );
834 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
835 }
836
837 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
838 $priorWritesPending = $this->writesOrCallbacksPending();
839 $this->mLastQuery = $sql;
840
841 $isWrite = $this->isWriteQuery( $sql );
842 if ( $isWrite ) {
843 $reason = $this->getReadOnlyReason();
844 if ( $reason !== false ) {
845 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
846 }
847 # Set a flag indicating that writes have been done
848 $this->mDoneWrites = microtime( true );
849 }
850
851 // Add trace comment to the begin of the sql string, right after the operator.
852 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
853 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
854
855 # Start implicit transactions that wrap the request if DBO_TRX is enabled
856 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX )
857 && $this->isTransactableQuery( $sql )
858 ) {
859 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
860 $this->mTrxAutomatic = true;
861 }
862
863 # Keep track of whether the transaction has write queries pending
864 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
865 $this->mTrxDoneWrites = true;
866 $this->trxProfiler->transactionWritingIn(
867 $this->mServer, $this->mDBname, $this->mTrxShortId );
868 }
869
870 if ( $this->debug() ) {
871 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
872 }
873
874 # Avoid fatals if close() was called
875 $this->assertOpen();
876
877 # Send the query to the server
878 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
879
880 # Try reconnecting if the connection was lost
881 if ( false === $ret && $this->wasErrorReissuable() ) {
882 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
883 # Stash the last error values before anything might clear them
884 $lastError = $this->lastError();
885 $lastErrno = $this->lastErrno();
886 # Update state tracking to reflect transaction loss due to disconnection
887 $this->handleTransactionLoss();
888 if ( $this->reconnect() ) {
889 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
890 $this->connLogger->warning( $msg );
891 $this->queryLogger->warning(
892 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
893
894 if ( !$recoverable ) {
895 # Callers may catch the exception and continue to use the DB
896 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
897 } else {
898 # Should be safe to silently retry the query
899 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
900 }
901 } else {
902 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
903 $this->connLogger->error( $msg );
904 }
905 }
906
907 if ( false === $ret ) {
908 # Deadlocks cause the entire transaction to abort, not just the statement.
909 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
910 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
911 if ( $this->wasDeadlock() ) {
912 if ( $this->explicitTrxActive() || $priorWritesPending ) {
913 $tempIgnore = false; // not recoverable
914 }
915 # Update state tracking to reflect transaction loss
916 $this->handleTransactionLoss();
917 }
918
919 $this->reportQueryError(
920 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
921 }
922
923 $res = $this->resultObject( $ret );
924
925 return $res;
926 }
927
928 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
929 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
930 # generalizeSQL() will probably cut down the query to reasonable
931 # logging size most of the time. The substr is really just a sanity check.
932 if ( $isMaster ) {
933 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
934 } else {
935 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
936 }
937
938 # Include query transaction state
939 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
940
941 $startTime = microtime( true );
942 $this->profiler->profileIn( $queryProf );
943 $ret = $this->doQuery( $commentedSql );
944 $this->profiler->profileOut( $queryProf );
945 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
946
947 unset( $queryProfSection ); // profile out (if set)
948
949 if ( $ret !== false ) {
950 $this->lastPing = $startTime;
951 if ( $isWrite && $this->mTrxLevel ) {
952 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
953 $this->mTrxWriteCallers[] = $fname;
954 }
955 }
956
957 if ( $sql === self::PING_QUERY ) {
958 $this->mRTTEstimate = $queryRuntime;
959 }
960
961 $this->trxProfiler->recordQueryCompletion(
962 $queryProf, $startTime, $isWrite, $this->affectedRows()
963 );
964 MWDebug::query( $sql, $fname, $isMaster, $queryRuntime );
965
966 return $ret;
967 }
968
969 /**
970 * Update the estimated run-time of a query, not counting large row lock times
971 *
972 * LoadBalancer can be set to rollback transactions that will create huge replication
973 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
974 * queries, like inserting a row can take a long time due to row locking. This method
975 * uses some simple heuristics to discount those cases.
976 *
977 * @param string $sql A SQL write query
978 * @param float $runtime Total runtime, including RTT
979 */
980 private function updateTrxWriteQueryTime( $sql, $runtime ) {
981 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
982 $indicativeOfReplicaRuntime = true;
983 if ( $runtime > self::SLOW_WRITE_SEC ) {
984 $verb = $this->getQueryVerb( $sql );
985 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
986 if ( $verb === 'INSERT' ) {
987 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
988 } elseif ( $verb === 'REPLACE' ) {
989 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
990 }
991 }
992
993 $this->mTrxWriteDuration += $runtime;
994 $this->mTrxWriteQueryCount += 1;
995 if ( $indicativeOfReplicaRuntime ) {
996 $this->mTrxWriteAdjDuration += $runtime;
997 $this->mTrxWriteAdjQueryCount += 1;
998 }
999 }
1000
1001 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1002 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1003 # Dropped connections also mean that named locks are automatically released.
1004 # Only allow error suppression in autocommit mode or when the lost transaction
1005 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1006 if ( $this->mNamedLocksHeld ) {
1007 return false; // possible critical section violation
1008 } elseif ( $sql === 'COMMIT' ) {
1009 return !$priorWritesPending; // nothing written anyway? (T127428)
1010 } elseif ( $sql === 'ROLLBACK' ) {
1011 return true; // transaction lost...which is also what was requested :)
1012 } elseif ( $this->explicitTrxActive() ) {
1013 return false; // don't drop atomocity
1014 } elseif ( $priorWritesPending ) {
1015 return false; // prior writes lost from implicit transaction
1016 }
1017
1018 return true;
1019 }
1020
1021 private function handleTransactionLoss() {
1022 $this->mTrxLevel = 0;
1023 $this->mTrxIdleCallbacks = []; // bug 65263
1024 $this->mTrxPreCommitCallbacks = []; // bug 65263
1025 try {
1026 // Handle callbacks in mTrxEndCallbacks
1027 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1028 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1029 return null;
1030 } catch ( Exception $e ) {
1031 // Already logged; move on...
1032 return $e;
1033 }
1034 }
1035
1036 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1037 if ( $this->ignoreErrors() || $tempIgnore ) {
1038 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1039 } else {
1040 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1041 $this->queryLogger->error(
1042 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1043 $this->getLogContext( [
1044 'method' => __METHOD__,
1045 'errno' => $errno,
1046 'error' => $error,
1047 'sql1line' => $sql1line,
1048 'fname' => $fname,
1049 ] )
1050 );
1051 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1052 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1053 }
1054 }
1055
1056 /**
1057 * Intended to be compatible with the PEAR::DB wrapper functions.
1058 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1059 *
1060 * ? = scalar value, quoted as necessary
1061 * ! = raw SQL bit (a function for instance)
1062 * & = filename; reads the file and inserts as a blob
1063 * (we don't use this though...)
1064 *
1065 * @param string $sql
1066 * @param string $func
1067 *
1068 * @return array
1069 */
1070 protected function prepare( $sql, $func = __METHOD__ ) {
1071 /* MySQL doesn't support prepared statements (yet), so just
1072 * pack up the query for reference. We'll manually replace
1073 * the bits later.
1074 */
1075 return [ 'query' => $sql, 'func' => $func ];
1076 }
1077
1078 /**
1079 * Free a prepared query, generated by prepare().
1080 * @param string $prepared
1081 */
1082 protected function freePrepared( $prepared ) {
1083 /* No-op by default */
1084 }
1085
1086 /**
1087 * Execute a prepared query with the various arguments
1088 * @param string $prepared The prepared sql
1089 * @param mixed $args Either an array here, or put scalars as varargs
1090 *
1091 * @return ResultWrapper
1092 */
1093 public function execute( $prepared, $args = null ) {
1094 if ( !is_array( $args ) ) {
1095 # Pull the var args
1096 $args = func_get_args();
1097 array_shift( $args );
1098 }
1099
1100 $sql = $this->fillPrepared( $prepared['query'], $args );
1101
1102 return $this->query( $sql, $prepared['func'] );
1103 }
1104
1105 /**
1106 * For faking prepared SQL statements on DBs that don't support it directly.
1107 *
1108 * @param string $preparedQuery A 'preparable' SQL statement
1109 * @param array $args Array of Arguments to fill it with
1110 * @return string Executable SQL
1111 */
1112 public function fillPrepared( $preparedQuery, $args ) {
1113 reset( $args );
1114 $this->preparedArgs =& $args;
1115
1116 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1117 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1118 }
1119
1120 /**
1121 * preg_callback func for fillPrepared()
1122 * The arguments should be in $this->preparedArgs and must not be touched
1123 * while we're doing this.
1124 *
1125 * @param array $matches
1126 * @throws DBUnexpectedError
1127 * @return string
1128 */
1129 protected function fillPreparedArg( $matches ) {
1130 switch ( $matches[1] ) {
1131 case '\\?':
1132 return '?';
1133 case '\\!':
1134 return '!';
1135 case '\\&':
1136 return '&';
1137 }
1138
1139 list( /* $n */, $arg ) = each( $this->preparedArgs );
1140
1141 switch ( $matches[1] ) {
1142 case '?':
1143 return $this->addQuotes( $arg );
1144 case '!':
1145 return $arg;
1146 case '&':
1147 # return $this->addQuotes( file_get_contents( $arg ) );
1148 throw new DBUnexpectedError(
1149 $this,
1150 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1151 );
1152 default:
1153 throw new DBUnexpectedError(
1154 $this,
1155 'Received invalid match. This should never happen!'
1156 );
1157 }
1158 }
1159
1160 public function freeResult( $res ) {
1161 }
1162
1163 public function selectField(
1164 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1165 ) {
1166 if ( $var === '*' ) { // sanity
1167 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1168 }
1169
1170 if ( !is_array( $options ) ) {
1171 $options = [ $options ];
1172 }
1173
1174 $options['LIMIT'] = 1;
1175
1176 $res = $this->select( $table, $var, $cond, $fname, $options );
1177 if ( $res === false || !$this->numRows( $res ) ) {
1178 return false;
1179 }
1180
1181 $row = $this->fetchRow( $res );
1182
1183 if ( $row !== false ) {
1184 return reset( $row );
1185 } else {
1186 return false;
1187 }
1188 }
1189
1190 public function selectFieldValues(
1191 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1192 ) {
1193 if ( $var === '*' ) { // sanity
1194 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1195 } elseif ( !is_string( $var ) ) { // sanity
1196 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1197 }
1198
1199 if ( !is_array( $options ) ) {
1200 $options = [ $options ];
1201 }
1202
1203 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1204 if ( $res === false ) {
1205 return false;
1206 }
1207
1208 $values = [];
1209 foreach ( $res as $row ) {
1210 $values[] = $row->$var;
1211 }
1212
1213 return $values;
1214 }
1215
1216 /**
1217 * Returns an optional USE INDEX clause to go after the table, and a
1218 * string to go at the end of the query.
1219 *
1220 * @param array $options Associative array of options to be turned into
1221 * an SQL query, valid keys are listed in the function.
1222 * @return array
1223 * @see DatabaseBase::select()
1224 */
1225 public function makeSelectOptions( $options ) {
1226 $preLimitTail = $postLimitTail = '';
1227 $startOpts = '';
1228
1229 $noKeyOptions = [];
1230
1231 foreach ( $options as $key => $option ) {
1232 if ( is_numeric( $key ) ) {
1233 $noKeyOptions[$option] = true;
1234 }
1235 }
1236
1237 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1238
1239 $preLimitTail .= $this->makeOrderBy( $options );
1240
1241 // if (isset($options['LIMIT'])) {
1242 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1243 // isset($options['OFFSET']) ? $options['OFFSET']
1244 // : false);
1245 // }
1246
1247 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1248 $postLimitTail .= ' FOR UPDATE';
1249 }
1250
1251 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1252 $postLimitTail .= ' LOCK IN SHARE MODE';
1253 }
1254
1255 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1256 $startOpts .= 'DISTINCT';
1257 }
1258
1259 # Various MySQL extensions
1260 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1261 $startOpts .= ' /*! STRAIGHT_JOIN */';
1262 }
1263
1264 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1265 $startOpts .= ' HIGH_PRIORITY';
1266 }
1267
1268 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1269 $startOpts .= ' SQL_BIG_RESULT';
1270 }
1271
1272 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1273 $startOpts .= ' SQL_BUFFER_RESULT';
1274 }
1275
1276 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1277 $startOpts .= ' SQL_SMALL_RESULT';
1278 }
1279
1280 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1281 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1282 }
1283
1284 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1285 $startOpts .= ' SQL_CACHE';
1286 }
1287
1288 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1289 $startOpts .= ' SQL_NO_CACHE';
1290 }
1291
1292 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1293 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1294 } else {
1295 $useIndex = '';
1296 }
1297 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1298 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1299 } else {
1300 $ignoreIndex = '';
1301 }
1302
1303 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1304 }
1305
1306 /**
1307 * Returns an optional GROUP BY with an optional HAVING
1308 *
1309 * @param array $options Associative array of options
1310 * @return string
1311 * @see DatabaseBase::select()
1312 * @since 1.21
1313 */
1314 public function makeGroupByWithHaving( $options ) {
1315 $sql = '';
1316 if ( isset( $options['GROUP BY'] ) ) {
1317 $gb = is_array( $options['GROUP BY'] )
1318 ? implode( ',', $options['GROUP BY'] )
1319 : $options['GROUP BY'];
1320 $sql .= ' GROUP BY ' . $gb;
1321 }
1322 if ( isset( $options['HAVING'] ) ) {
1323 $having = is_array( $options['HAVING'] )
1324 ? $this->makeList( $options['HAVING'], LIST_AND )
1325 : $options['HAVING'];
1326 $sql .= ' HAVING ' . $having;
1327 }
1328
1329 return $sql;
1330 }
1331
1332 /**
1333 * Returns an optional ORDER BY
1334 *
1335 * @param array $options Associative array of options
1336 * @return string
1337 * @see DatabaseBase::select()
1338 * @since 1.21
1339 */
1340 public function makeOrderBy( $options ) {
1341 if ( isset( $options['ORDER BY'] ) ) {
1342 $ob = is_array( $options['ORDER BY'] )
1343 ? implode( ',', $options['ORDER BY'] )
1344 : $options['ORDER BY'];
1345
1346 return ' ORDER BY ' . $ob;
1347 }
1348
1349 return '';
1350 }
1351
1352 // See IDatabase::select for the docs for this function
1353 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1354 $options = [], $join_conds = [] ) {
1355 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1356
1357 return $this->query( $sql, $fname );
1358 }
1359
1360 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1361 $options = [], $join_conds = []
1362 ) {
1363 if ( is_array( $vars ) ) {
1364 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1365 }
1366
1367 $options = (array)$options;
1368 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1369 ? $options['USE INDEX']
1370 : [];
1371 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1372 ? $options['IGNORE INDEX']
1373 : [];
1374
1375 if ( is_array( $table ) ) {
1376 $from = ' FROM ' .
1377 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1378 } elseif ( $table != '' ) {
1379 if ( $table[0] == ' ' ) {
1380 $from = ' FROM ' . $table;
1381 } else {
1382 $from = ' FROM ' .
1383 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1384 }
1385 } else {
1386 $from = '';
1387 }
1388
1389 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1390 $this->makeSelectOptions( $options );
1391
1392 if ( !empty( $conds ) ) {
1393 if ( is_array( $conds ) ) {
1394 $conds = $this->makeList( $conds, LIST_AND );
1395 }
1396 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1397 } else {
1398 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1399 }
1400
1401 if ( isset( $options['LIMIT'] ) ) {
1402 $sql = $this->limitResult( $sql, $options['LIMIT'],
1403 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1404 }
1405 $sql = "$sql $postLimitTail";
1406
1407 if ( isset( $options['EXPLAIN'] ) ) {
1408 $sql = 'EXPLAIN ' . $sql;
1409 }
1410
1411 return $sql;
1412 }
1413
1414 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1415 $options = [], $join_conds = []
1416 ) {
1417 $options = (array)$options;
1418 $options['LIMIT'] = 1;
1419 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1420
1421 if ( $res === false ) {
1422 return false;
1423 }
1424
1425 if ( !$this->numRows( $res ) ) {
1426 return false;
1427 }
1428
1429 $obj = $this->fetchObject( $res );
1430
1431 return $obj;
1432 }
1433
1434 public function estimateRowCount(
1435 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1436 ) {
1437 $rows = 0;
1438 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1439
1440 if ( $res ) {
1441 $row = $this->fetchRow( $res );
1442 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1443 }
1444
1445 return $rows;
1446 }
1447
1448 public function selectRowCount(
1449 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1450 ) {
1451 $rows = 0;
1452 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1453 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1454
1455 if ( $res ) {
1456 $row = $this->fetchRow( $res );
1457 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1458 }
1459
1460 return $rows;
1461 }
1462
1463 /**
1464 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1465 * It's only slightly flawed. Don't use for anything important.
1466 *
1467 * @param string $sql A SQL Query
1468 *
1469 * @return string
1470 */
1471 protected static function generalizeSQL( $sql ) {
1472 # This does the same as the regexp below would do, but in such a way
1473 # as to avoid crashing php on some large strings.
1474 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1475
1476 $sql = str_replace( "\\\\", '', $sql );
1477 $sql = str_replace( "\\'", '', $sql );
1478 $sql = str_replace( "\\\"", '', $sql );
1479 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1480 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1481
1482 # All newlines, tabs, etc replaced by single space
1483 $sql = preg_replace( '/\s+/', ' ', $sql );
1484
1485 # All numbers => N,
1486 # except the ones surrounded by characters, e.g. l10n
1487 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1488 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1489
1490 return $sql;
1491 }
1492
1493 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1494 $info = $this->fieldInfo( $table, $field );
1495
1496 return (bool)$info;
1497 }
1498
1499 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1500 if ( !$this->tableExists( $table ) ) {
1501 return null;
1502 }
1503
1504 $info = $this->indexInfo( $table, $index, $fname );
1505 if ( is_null( $info ) ) {
1506 return null;
1507 } else {
1508 return $info !== false;
1509 }
1510 }
1511
1512 public function tableExists( $table, $fname = __METHOD__ ) {
1513 $table = $this->tableName( $table );
1514 $old = $this->ignoreErrors( true );
1515 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1516 $this->ignoreErrors( $old );
1517
1518 return (bool)$res;
1519 }
1520
1521 public function indexUnique( $table, $index ) {
1522 $indexInfo = $this->indexInfo( $table, $index );
1523
1524 if ( !$indexInfo ) {
1525 return null;
1526 }
1527
1528 return !$indexInfo[0]->Non_unique;
1529 }
1530
1531 /**
1532 * Helper for DatabaseBase::insert().
1533 *
1534 * @param array $options
1535 * @return string
1536 */
1537 protected function makeInsertOptions( $options ) {
1538 return implode( ' ', $options );
1539 }
1540
1541 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1542 # No rows to insert, easy just return now
1543 if ( !count( $a ) ) {
1544 return true;
1545 }
1546
1547 $table = $this->tableName( $table );
1548
1549 if ( !is_array( $options ) ) {
1550 $options = [ $options ];
1551 }
1552
1553 $fh = null;
1554 if ( isset( $options['fileHandle'] ) ) {
1555 $fh = $options['fileHandle'];
1556 }
1557 $options = $this->makeInsertOptions( $options );
1558
1559 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1560 $multi = true;
1561 $keys = array_keys( $a[0] );
1562 } else {
1563 $multi = false;
1564 $keys = array_keys( $a );
1565 }
1566
1567 $sql = 'INSERT ' . $options .
1568 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1569
1570 if ( $multi ) {
1571 $first = true;
1572 foreach ( $a as $row ) {
1573 if ( $first ) {
1574 $first = false;
1575 } else {
1576 $sql .= ',';
1577 }
1578 $sql .= '(' . $this->makeList( $row ) . ')';
1579 }
1580 } else {
1581 $sql .= '(' . $this->makeList( $a ) . ')';
1582 }
1583
1584 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1585 return false;
1586 } elseif ( $fh !== null ) {
1587 return true;
1588 }
1589
1590 return (bool)$this->query( $sql, $fname );
1591 }
1592
1593 /**
1594 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1595 *
1596 * @param array $options
1597 * @return array
1598 */
1599 protected function makeUpdateOptionsArray( $options ) {
1600 if ( !is_array( $options ) ) {
1601 $options = [ $options ];
1602 }
1603
1604 $opts = [];
1605
1606 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1607 $opts[] = $this->lowPriorityOption();
1608 }
1609
1610 if ( in_array( 'IGNORE', $options ) ) {
1611 $opts[] = 'IGNORE';
1612 }
1613
1614 return $opts;
1615 }
1616
1617 /**
1618 * Make UPDATE options for the DatabaseBase::update function
1619 *
1620 * @param array $options The options passed to DatabaseBase::update
1621 * @return string
1622 */
1623 protected function makeUpdateOptions( $options ) {
1624 $opts = $this->makeUpdateOptionsArray( $options );
1625
1626 return implode( ' ', $opts );
1627 }
1628
1629 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1630 $table = $this->tableName( $table );
1631 $opts = $this->makeUpdateOptions( $options );
1632 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1633
1634 if ( $conds !== [] && $conds !== '*' ) {
1635 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1636 }
1637
1638 return $this->query( $sql, $fname );
1639 }
1640
1641 public function makeList( $a, $mode = LIST_COMMA ) {
1642 if ( !is_array( $a ) ) {
1643 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1644 }
1645
1646 $first = true;
1647 $list = '';
1648
1649 foreach ( $a as $field => $value ) {
1650 if ( !$first ) {
1651 if ( $mode == LIST_AND ) {
1652 $list .= ' AND ';
1653 } elseif ( $mode == LIST_OR ) {
1654 $list .= ' OR ';
1655 } else {
1656 $list .= ',';
1657 }
1658 } else {
1659 $first = false;
1660 }
1661
1662 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1663 $list .= "($value)";
1664 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1665 $list .= "$value";
1666 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1667 // Remove null from array to be handled separately if found
1668 $includeNull = false;
1669 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1670 $includeNull = true;
1671 unset( $value[$nullKey] );
1672 }
1673 if ( count( $value ) == 0 && !$includeNull ) {
1674 throw new InvalidArgumentException( __METHOD__ . ": empty input for field $field" );
1675 } elseif ( count( $value ) == 0 ) {
1676 // only check if $field is null
1677 $list .= "$field IS NULL";
1678 } else {
1679 // IN clause contains at least one valid element
1680 if ( $includeNull ) {
1681 // Group subconditions to ensure correct precedence
1682 $list .= '(';
1683 }
1684 if ( count( $value ) == 1 ) {
1685 // Special-case single values, as IN isn't terribly efficient
1686 // Don't necessarily assume the single key is 0; we don't
1687 // enforce linear numeric ordering on other arrays here.
1688 $value = array_values( $value )[0];
1689 $list .= $field . " = " . $this->addQuotes( $value );
1690 } else {
1691 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1692 }
1693 // if null present in array, append IS NULL
1694 if ( $includeNull ) {
1695 $list .= " OR $field IS NULL)";
1696 }
1697 }
1698 } elseif ( $value === null ) {
1699 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1700 $list .= "$field IS ";
1701 } elseif ( $mode == LIST_SET ) {
1702 $list .= "$field = ";
1703 }
1704 $list .= 'NULL';
1705 } else {
1706 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1707 $list .= "$field = ";
1708 }
1709 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1710 }
1711 }
1712
1713 return $list;
1714 }
1715
1716 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1717 $conds = [];
1718
1719 foreach ( $data as $base => $sub ) {
1720 if ( count( $sub ) ) {
1721 $conds[] = $this->makeList(
1722 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1723 LIST_AND );
1724 }
1725 }
1726
1727 if ( $conds ) {
1728 return $this->makeList( $conds, LIST_OR );
1729 } else {
1730 // Nothing to search for...
1731 return false;
1732 }
1733 }
1734
1735 /**
1736 * Return aggregated value alias
1737 *
1738 * @param array $valuedata
1739 * @param string $valuename
1740 *
1741 * @return string
1742 */
1743 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1744 return $valuename;
1745 }
1746
1747 public function bitNot( $field ) {
1748 return "(~$field)";
1749 }
1750
1751 public function bitAnd( $fieldLeft, $fieldRight ) {
1752 return "($fieldLeft & $fieldRight)";
1753 }
1754
1755 public function bitOr( $fieldLeft, $fieldRight ) {
1756 return "($fieldLeft | $fieldRight)";
1757 }
1758
1759 public function buildConcat( $stringList ) {
1760 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1761 }
1762
1763 public function buildGroupConcatField(
1764 $delim, $table, $field, $conds = '', $join_conds = []
1765 ) {
1766 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1767
1768 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1769 }
1770
1771 /**
1772 * @param string $field Field or column to cast
1773 * @return string
1774 * @since 1.28
1775 */
1776 public function buildStringCast( $field ) {
1777 return $field;
1778 }
1779
1780 public function selectDB( $db ) {
1781 # Stub. Shouldn't cause serious problems if it's not overridden, but
1782 # if your database engine supports a concept similar to MySQL's
1783 # databases you may as well.
1784 $this->mDBname = $db;
1785
1786 return true;
1787 }
1788
1789 public function getDBname() {
1790 return $this->mDBname;
1791 }
1792
1793 public function getServer() {
1794 return $this->mServer;
1795 }
1796
1797 /**
1798 * Format a table name ready for use in constructing an SQL query
1799 *
1800 * This does two important things: it quotes the table names to clean them up,
1801 * and it adds a table prefix if only given a table name with no quotes.
1802 *
1803 * All functions of this object which require a table name call this function
1804 * themselves. Pass the canonical name to such functions. This is only needed
1805 * when calling query() directly.
1806 *
1807 * @note This function does not sanitize user input. It is not safe to use
1808 * this function to escape user input.
1809 * @param string $name Database table name
1810 * @param string $format One of:
1811 * quoted - Automatically pass the table name through addIdentifierQuotes()
1812 * so that it can be used in a query.
1813 * raw - Do not add identifier quotes to the table name
1814 * @return string Full database name
1815 */
1816 public function tableName( $name, $format = 'quoted' ) {
1817 # Skip the entire process when we have a string quoted on both ends.
1818 # Note that we check the end so that we will still quote any use of
1819 # use of `database`.table. But won't break things if someone wants
1820 # to query a database table with a dot in the name.
1821 if ( $this->isQuotedIdentifier( $name ) ) {
1822 return $name;
1823 }
1824
1825 # Lets test for any bits of text that should never show up in a table
1826 # name. Basically anything like JOIN or ON which are actually part of
1827 # SQL queries, but may end up inside of the table value to combine
1828 # sql. Such as how the API is doing.
1829 # Note that we use a whitespace test rather than a \b test to avoid
1830 # any remote case where a word like on may be inside of a table name
1831 # surrounded by symbols which may be considered word breaks.
1832 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1833 return $name;
1834 }
1835
1836 # Split database and table into proper variables.
1837 # We reverse the explode so that database.table and table both output
1838 # the correct table.
1839 $dbDetails = explode( '.', $name, 3 );
1840 if ( count( $dbDetails ) == 3 ) {
1841 list( $database, $schema, $table ) = $dbDetails;
1842 # We don't want any prefix added in this case
1843 $prefix = '';
1844 } elseif ( count( $dbDetails ) == 2 ) {
1845 list( $database, $table ) = $dbDetails;
1846 # We don't want any prefix added in this case
1847 # In dbs that support it, $database may actually be the schema
1848 # but that doesn't affect any of the functionality here
1849 $prefix = '';
1850 $schema = null;
1851 } else {
1852 list( $table ) = $dbDetails;
1853 if ( isset( $this->tableAliases[$table] ) ) {
1854 $database = $this->tableAliases[$table]['dbname'];
1855 $schema = is_string( $this->tableAliases[$table]['schema'] )
1856 ? $this->tableAliases[$table]['schema']
1857 : $this->mSchema;
1858 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1859 ? $this->tableAliases[$table]['prefix']
1860 : $this->mTablePrefix;
1861 } else {
1862 $database = null;
1863 $schema = $this->mSchema; # Default schema
1864 $prefix = $this->mTablePrefix; # Default prefix
1865 }
1866 }
1867
1868 # Quote $table and apply the prefix if not quoted.
1869 # $tableName might be empty if this is called from Database::replaceVars()
1870 $tableName = "{$prefix}{$table}";
1871 if ( $format == 'quoted'
1872 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1873 ) {
1874 $tableName = $this->addIdentifierQuotes( $tableName );
1875 }
1876
1877 # Quote $schema and merge it with the table name if needed
1878 if ( strlen( $schema ) ) {
1879 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1880 $schema = $this->addIdentifierQuotes( $schema );
1881 }
1882 $tableName = $schema . '.' . $tableName;
1883 }
1884
1885 # Quote $database and merge it with the table name if needed
1886 if ( $database !== null ) {
1887 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1888 $database = $this->addIdentifierQuotes( $database );
1889 }
1890 $tableName = $database . '.' . $tableName;
1891 }
1892
1893 return $tableName;
1894 }
1895
1896 /**
1897 * Fetch a number of table names into an array
1898 * This is handy when you need to construct SQL for joins
1899 *
1900 * Example:
1901 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1902 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1903 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1904 *
1905 * @return array
1906 */
1907 public function tableNames() {
1908 $inArray = func_get_args();
1909 $retVal = [];
1910
1911 foreach ( $inArray as $name ) {
1912 $retVal[$name] = $this->tableName( $name );
1913 }
1914
1915 return $retVal;
1916 }
1917
1918 /**
1919 * Fetch a number of table names into an zero-indexed numerical array
1920 * This is handy when you need to construct SQL for joins
1921 *
1922 * Example:
1923 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1924 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1925 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1926 *
1927 * @return array
1928 */
1929 public function tableNamesN() {
1930 $inArray = func_get_args();
1931 $retVal = [];
1932
1933 foreach ( $inArray as $name ) {
1934 $retVal[] = $this->tableName( $name );
1935 }
1936
1937 return $retVal;
1938 }
1939
1940 /**
1941 * Get an aliased table name
1942 * e.g. tableName AS newTableName
1943 *
1944 * @param string $name Table name, see tableName()
1945 * @param string|bool $alias Alias (optional)
1946 * @return string SQL name for aliased table. Will not alias a table to its own name
1947 */
1948 public function tableNameWithAlias( $name, $alias = false ) {
1949 if ( !$alias || $alias == $name ) {
1950 return $this->tableName( $name );
1951 } else {
1952 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1953 }
1954 }
1955
1956 /**
1957 * Gets an array of aliased table names
1958 *
1959 * @param array $tables [ [alias] => table ]
1960 * @return string[] See tableNameWithAlias()
1961 */
1962 public function tableNamesWithAlias( $tables ) {
1963 $retval = [];
1964 foreach ( $tables as $alias => $table ) {
1965 if ( is_numeric( $alias ) ) {
1966 $alias = $table;
1967 }
1968 $retval[] = $this->tableNameWithAlias( $table, $alias );
1969 }
1970
1971 return $retval;
1972 }
1973
1974 /**
1975 * Get an aliased field name
1976 * e.g. fieldName AS newFieldName
1977 *
1978 * @param string $name Field name
1979 * @param string|bool $alias Alias (optional)
1980 * @return string SQL name for aliased field. Will not alias a field to its own name
1981 */
1982 public function fieldNameWithAlias( $name, $alias = false ) {
1983 if ( !$alias || (string)$alias === (string)$name ) {
1984 return $name;
1985 } else {
1986 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1987 }
1988 }
1989
1990 /**
1991 * Gets an array of aliased field names
1992 *
1993 * @param array $fields [ [alias] => field ]
1994 * @return string[] See fieldNameWithAlias()
1995 */
1996 public function fieldNamesWithAlias( $fields ) {
1997 $retval = [];
1998 foreach ( $fields as $alias => $field ) {
1999 if ( is_numeric( $alias ) ) {
2000 $alias = $field;
2001 }
2002 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2003 }
2004
2005 return $retval;
2006 }
2007
2008 /**
2009 * Get the aliased table name clause for a FROM clause
2010 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2011 *
2012 * @param array $tables ( [alias] => table )
2013 * @param array $use_index Same as for select()
2014 * @param array $ignore_index Same as for select()
2015 * @param array $join_conds Same as for select()
2016 * @return string
2017 */
2018 protected function tableNamesWithIndexClauseOrJOIN(
2019 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2020 ) {
2021 $ret = [];
2022 $retJOIN = [];
2023 $use_index = (array)$use_index;
2024 $ignore_index = (array)$ignore_index;
2025 $join_conds = (array)$join_conds;
2026
2027 foreach ( $tables as $alias => $table ) {
2028 if ( !is_string( $alias ) ) {
2029 // No alias? Set it equal to the table name
2030 $alias = $table;
2031 }
2032 // Is there a JOIN clause for this table?
2033 if ( isset( $join_conds[$alias] ) ) {
2034 list( $joinType, $conds ) = $join_conds[$alias];
2035 $tableClause = $joinType;
2036 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2037 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2038 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2039 if ( $use != '' ) {
2040 $tableClause .= ' ' . $use;
2041 }
2042 }
2043 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2044 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2045 if ( $ignore != '' ) {
2046 $tableClause .= ' ' . $ignore;
2047 }
2048 }
2049 $on = $this->makeList( (array)$conds, LIST_AND );
2050 if ( $on != '' ) {
2051 $tableClause .= ' ON (' . $on . ')';
2052 }
2053
2054 $retJOIN[] = $tableClause;
2055 } elseif ( isset( $use_index[$alias] ) ) {
2056 // Is there an INDEX clause for this table?
2057 $tableClause = $this->tableNameWithAlias( $table, $alias );
2058 $tableClause .= ' ' . $this->useIndexClause(
2059 implode( ',', (array)$use_index[$alias] )
2060 );
2061
2062 $ret[] = $tableClause;
2063 } elseif ( isset( $ignore_index[$alias] ) ) {
2064 // Is there an INDEX clause for this table?
2065 $tableClause = $this->tableNameWithAlias( $table, $alias );
2066 $tableClause .= ' ' . $this->ignoreIndexClause(
2067 implode( ',', (array)$ignore_index[$alias] )
2068 );
2069
2070 $ret[] = $tableClause;
2071 } else {
2072 $tableClause = $this->tableNameWithAlias( $table, $alias );
2073
2074 $ret[] = $tableClause;
2075 }
2076 }
2077
2078 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2079 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2080 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2081
2082 // Compile our final table clause
2083 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2084 }
2085
2086 /**
2087 * Get the name of an index in a given table.
2088 *
2089 * @param string $index
2090 * @return string
2091 */
2092 protected function indexName( $index ) {
2093 // Backwards-compatibility hack
2094 $renamed = [
2095 'ar_usertext_timestamp' => 'usertext_timestamp',
2096 'un_user_id' => 'user_id',
2097 'un_user_ip' => 'user_ip',
2098 ];
2099
2100 if ( isset( $renamed[$index] ) ) {
2101 return $renamed[$index];
2102 } else {
2103 return $index;
2104 }
2105 }
2106
2107 public function addQuotes( $s ) {
2108 if ( $s instanceof Blob ) {
2109 $s = $s->fetch();
2110 }
2111 if ( $s === null ) {
2112 return 'NULL';
2113 } else {
2114 # This will also quote numeric values. This should be harmless,
2115 # and protects against weird problems that occur when they really
2116 # _are_ strings such as article titles and string->number->string
2117 # conversion is not 1:1.
2118 return "'" . $this->strencode( $s ) . "'";
2119 }
2120 }
2121
2122 /**
2123 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2124 * MySQL uses `backticks` while basically everything else uses double quotes.
2125 * Since MySQL is the odd one out here the double quotes are our generic
2126 * and we implement backticks in DatabaseMysql.
2127 *
2128 * @param string $s
2129 * @return string
2130 */
2131 public function addIdentifierQuotes( $s ) {
2132 return '"' . str_replace( '"', '""', $s ) . '"';
2133 }
2134
2135 /**
2136 * Returns if the given identifier looks quoted or not according to
2137 * the database convention for quoting identifiers .
2138 *
2139 * @note Do not use this to determine if untrusted input is safe.
2140 * A malicious user can trick this function.
2141 * @param string $name
2142 * @return bool
2143 */
2144 public function isQuotedIdentifier( $name ) {
2145 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2146 }
2147
2148 /**
2149 * @param string $s
2150 * @return string
2151 */
2152 protected function escapeLikeInternal( $s ) {
2153 return addcslashes( $s, '\%_' );
2154 }
2155
2156 public function buildLike() {
2157 $params = func_get_args();
2158
2159 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2160 $params = $params[0];
2161 }
2162
2163 $s = '';
2164
2165 foreach ( $params as $value ) {
2166 if ( $value instanceof LikeMatch ) {
2167 $s .= $value->toString();
2168 } else {
2169 $s .= $this->escapeLikeInternal( $value );
2170 }
2171 }
2172
2173 return " LIKE {$this->addQuotes( $s )} ";
2174 }
2175
2176 public function anyChar() {
2177 return new LikeMatch( '_' );
2178 }
2179
2180 public function anyString() {
2181 return new LikeMatch( '%' );
2182 }
2183
2184 public function nextSequenceValue( $seqName ) {
2185 return null;
2186 }
2187
2188 /**
2189 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2190 * is only needed because a) MySQL must be as efficient as possible due to
2191 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2192 * which index to pick. Anyway, other databases might have different
2193 * indexes on a given table. So don't bother overriding this unless you're
2194 * MySQL.
2195 * @param string $index
2196 * @return string
2197 */
2198 public function useIndexClause( $index ) {
2199 return '';
2200 }
2201
2202 /**
2203 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2204 * is only needed because a) MySQL must be as efficient as possible due to
2205 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2206 * which index to pick. Anyway, other databases might have different
2207 * indexes on a given table. So don't bother overriding this unless you're
2208 * MySQL.
2209 * @param string $index
2210 * @return string
2211 */
2212 public function ignoreIndexClause( $index ) {
2213 return '';
2214 }
2215
2216 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2217 $quotedTable = $this->tableName( $table );
2218
2219 if ( count( $rows ) == 0 ) {
2220 return;
2221 }
2222
2223 # Single row case
2224 if ( !is_array( reset( $rows ) ) ) {
2225 $rows = [ $rows ];
2226 }
2227
2228 // @FXIME: this is not atomic, but a trx would break affectedRows()
2229 foreach ( $rows as $row ) {
2230 # Delete rows which collide
2231 if ( $uniqueIndexes ) {
2232 $sql = "DELETE FROM $quotedTable WHERE ";
2233 $first = true;
2234 foreach ( $uniqueIndexes as $index ) {
2235 if ( $first ) {
2236 $first = false;
2237 $sql .= '( ';
2238 } else {
2239 $sql .= ' ) OR ( ';
2240 }
2241 if ( is_array( $index ) ) {
2242 $first2 = true;
2243 foreach ( $index as $col ) {
2244 if ( $first2 ) {
2245 $first2 = false;
2246 } else {
2247 $sql .= ' AND ';
2248 }
2249 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2250 }
2251 } else {
2252 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2253 }
2254 }
2255 $sql .= ' )';
2256 $this->query( $sql, $fname );
2257 }
2258
2259 # Now insert the row
2260 $this->insert( $table, $row, $fname );
2261 }
2262 }
2263
2264 /**
2265 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2266 * statement.
2267 *
2268 * @param string $table Table name
2269 * @param array|string $rows Row(s) to insert
2270 * @param string $fname Caller function name
2271 *
2272 * @return ResultWrapper
2273 */
2274 protected function nativeReplace( $table, $rows, $fname ) {
2275 $table = $this->tableName( $table );
2276
2277 # Single row case
2278 if ( !is_array( reset( $rows ) ) ) {
2279 $rows = [ $rows ];
2280 }
2281
2282 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2283 $first = true;
2284
2285 foreach ( $rows as $row ) {
2286 if ( $first ) {
2287 $first = false;
2288 } else {
2289 $sql .= ',';
2290 }
2291
2292 $sql .= '(' . $this->makeList( $row ) . ')';
2293 }
2294
2295 return $this->query( $sql, $fname );
2296 }
2297
2298 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2299 $fname = __METHOD__
2300 ) {
2301 if ( !count( $rows ) ) {
2302 return true; // nothing to do
2303 }
2304
2305 if ( !is_array( reset( $rows ) ) ) {
2306 $rows = [ $rows ];
2307 }
2308
2309 if ( count( $uniqueIndexes ) ) {
2310 $clauses = []; // list WHERE clauses that each identify a single row
2311 foreach ( $rows as $row ) {
2312 foreach ( $uniqueIndexes as $index ) {
2313 $index = is_array( $index ) ? $index : [ $index ]; // columns
2314 $rowKey = []; // unique key to this row
2315 foreach ( $index as $column ) {
2316 $rowKey[$column] = $row[$column];
2317 }
2318 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2319 }
2320 }
2321 $where = [ $this->makeList( $clauses, LIST_OR ) ];
2322 } else {
2323 $where = false;
2324 }
2325
2326 $useTrx = !$this->mTrxLevel;
2327 if ( $useTrx ) {
2328 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2329 }
2330 try {
2331 # Update any existing conflicting row(s)
2332 if ( $where !== false ) {
2333 $ok = $this->update( $table, $set, $where, $fname );
2334 } else {
2335 $ok = true;
2336 }
2337 # Now insert any non-conflicting row(s)
2338 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2339 } catch ( Exception $e ) {
2340 if ( $useTrx ) {
2341 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2342 }
2343 throw $e;
2344 }
2345 if ( $useTrx ) {
2346 $this->commit( $fname, self::FLUSHING_INTERNAL );
2347 }
2348
2349 return $ok;
2350 }
2351
2352 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2353 $fname = __METHOD__
2354 ) {
2355 if ( !$conds ) {
2356 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2357 }
2358
2359 $delTable = $this->tableName( $delTable );
2360 $joinTable = $this->tableName( $joinTable );
2361 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2362 if ( $conds != '*' ) {
2363 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2364 }
2365 $sql .= ')';
2366
2367 $this->query( $sql, $fname );
2368 }
2369
2370 /**
2371 * Returns the size of a text field, or -1 for "unlimited"
2372 *
2373 * @param string $table
2374 * @param string $field
2375 * @return int
2376 */
2377 public function textFieldSize( $table, $field ) {
2378 $table = $this->tableName( $table );
2379 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2380 $res = $this->query( $sql, __METHOD__ );
2381 $row = $this->fetchObject( $res );
2382
2383 $m = [];
2384
2385 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2386 $size = $m[1];
2387 } else {
2388 $size = -1;
2389 }
2390
2391 return $size;
2392 }
2393
2394 /**
2395 * A string to insert into queries to show that they're low-priority, like
2396 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2397 * string and nothing bad should happen.
2398 *
2399 * @return string Returns the text of the low priority option if it is
2400 * supported, or a blank string otherwise
2401 */
2402 public function lowPriorityOption() {
2403 return '';
2404 }
2405
2406 public function delete( $table, $conds, $fname = __METHOD__ ) {
2407 if ( !$conds ) {
2408 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2409 }
2410
2411 $table = $this->tableName( $table );
2412 $sql = "DELETE FROM $table";
2413
2414 if ( $conds != '*' ) {
2415 if ( is_array( $conds ) ) {
2416 $conds = $this->makeList( $conds, LIST_AND );
2417 }
2418 $sql .= ' WHERE ' . $conds;
2419 }
2420
2421 return $this->query( $sql, $fname );
2422 }
2423
2424 public function insertSelect(
2425 $destTable, $srcTable, $varMap, $conds,
2426 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2427 ) {
2428 if ( $this->cliMode ) {
2429 // For massive migrations with downtime, we don't want to select everything
2430 // into memory and OOM, so do all this native on the server side if possible.
2431 return $this->nativeInsertSelect(
2432 $destTable,
2433 $srcTable,
2434 $varMap,
2435 $conds,
2436 $fname,
2437 $insertOptions,
2438 $selectOptions
2439 );
2440 }
2441
2442 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2443 // on only the master (without needing row-based-replication). It also makes it easy to
2444 // know how big the INSERT is going to be.
2445 $fields = [];
2446 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2447 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2448 }
2449 $selectOptions[] = 'FOR UPDATE';
2450 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2451 if ( !$res ) {
2452 return false;
2453 }
2454
2455 $rows = [];
2456 foreach ( $res as $row ) {
2457 $rows[] = (array)$row;
2458 }
2459
2460 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2461 }
2462
2463 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2464 $fname = __METHOD__,
2465 $insertOptions = [], $selectOptions = []
2466 ) {
2467 $destTable = $this->tableName( $destTable );
2468
2469 if ( !is_array( $insertOptions ) ) {
2470 $insertOptions = [ $insertOptions ];
2471 }
2472
2473 $insertOptions = $this->makeInsertOptions( $insertOptions );
2474
2475 if ( !is_array( $selectOptions ) ) {
2476 $selectOptions = [ $selectOptions ];
2477 }
2478
2479 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2480 $selectOptions );
2481
2482 if ( is_array( $srcTable ) ) {
2483 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2484 } else {
2485 $srcTable = $this->tableName( $srcTable );
2486 }
2487
2488 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2489 " SELECT $startOpts " . implode( ',', $varMap ) .
2490 " FROM $srcTable $useIndex $ignoreIndex ";
2491
2492 if ( $conds != '*' ) {
2493 if ( is_array( $conds ) ) {
2494 $conds = $this->makeList( $conds, LIST_AND );
2495 }
2496 $sql .= " WHERE $conds";
2497 }
2498
2499 $sql .= " $tailOpts";
2500
2501 return $this->query( $sql, $fname );
2502 }
2503
2504 /**
2505 * Construct a LIMIT query with optional offset. This is used for query
2506 * pages. The SQL should be adjusted so that only the first $limit rows
2507 * are returned. If $offset is provided as well, then the first $offset
2508 * rows should be discarded, and the next $limit rows should be returned.
2509 * If the result of the query is not ordered, then the rows to be returned
2510 * are theoretically arbitrary.
2511 *
2512 * $sql is expected to be a SELECT, if that makes a difference.
2513 *
2514 * The version provided by default works in MySQL and SQLite. It will very
2515 * likely need to be overridden for most other DBMSes.
2516 *
2517 * @param string $sql SQL query we will append the limit too
2518 * @param int $limit The SQL limit
2519 * @param int|bool $offset The SQL offset (default false)
2520 * @throws DBUnexpectedError
2521 * @return string
2522 */
2523 public function limitResult( $sql, $limit, $offset = false ) {
2524 if ( !is_numeric( $limit ) ) {
2525 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2526 }
2527
2528 return "$sql LIMIT "
2529 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2530 . "{$limit} ";
2531 }
2532
2533 public function unionSupportsOrderAndLimit() {
2534 return true; // True for almost every DB supported
2535 }
2536
2537 public function unionQueries( $sqls, $all ) {
2538 $glue = $all ? ') UNION ALL (' : ') UNION (';
2539
2540 return '(' . implode( $glue, $sqls ) . ')';
2541 }
2542
2543 public function conditional( $cond, $trueVal, $falseVal ) {
2544 if ( is_array( $cond ) ) {
2545 $cond = $this->makeList( $cond, LIST_AND );
2546 }
2547
2548 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2549 }
2550
2551 public function strreplace( $orig, $old, $new ) {
2552 return "REPLACE({$orig}, {$old}, {$new})";
2553 }
2554
2555 public function getServerUptime() {
2556 return 0;
2557 }
2558
2559 public function wasDeadlock() {
2560 return false;
2561 }
2562
2563 public function wasLockTimeout() {
2564 return false;
2565 }
2566
2567 public function wasErrorReissuable() {
2568 return false;
2569 }
2570
2571 public function wasReadOnlyError() {
2572 return false;
2573 }
2574
2575 /**
2576 * Determines if the given query error was a connection drop
2577 * STUB
2578 *
2579 * @param integer|string $errno
2580 * @return bool
2581 */
2582 public function wasConnectionError( $errno ) {
2583 return false;
2584 }
2585
2586 /**
2587 * Perform a deadlock-prone transaction.
2588 *
2589 * This function invokes a callback function to perform a set of write
2590 * queries. If a deadlock occurs during the processing, the transaction
2591 * will be rolled back and the callback function will be called again.
2592 *
2593 * Avoid using this method outside of Job or Maintenance classes.
2594 *
2595 * Usage:
2596 * $dbw->deadlockLoop( callback, ... );
2597 *
2598 * Extra arguments are passed through to the specified callback function.
2599 * This method requires that no transactions are already active to avoid
2600 * causing premature commits or exceptions.
2601 *
2602 * Returns whatever the callback function returned on its successful,
2603 * iteration, or false on error, for example if the retry limit was
2604 * reached.
2605 *
2606 * @return mixed
2607 * @throws DBUnexpectedError
2608 * @throws Exception
2609 */
2610 public function deadlockLoop() {
2611 $args = func_get_args();
2612 $function = array_shift( $args );
2613 $tries = self::DEADLOCK_TRIES;
2614
2615 $this->begin( __METHOD__ );
2616
2617 $retVal = null;
2618 /** @var Exception $e */
2619 $e = null;
2620 do {
2621 try {
2622 $retVal = call_user_func_array( $function, $args );
2623 break;
2624 } catch ( DBQueryError $e ) {
2625 if ( $this->wasDeadlock() ) {
2626 // Retry after a randomized delay
2627 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2628 } else {
2629 // Throw the error back up
2630 throw $e;
2631 }
2632 }
2633 } while ( --$tries > 0 );
2634
2635 if ( $tries <= 0 ) {
2636 // Too many deadlocks; give up
2637 $this->rollback( __METHOD__ );
2638 throw $e;
2639 } else {
2640 $this->commit( __METHOD__ );
2641
2642 return $retVal;
2643 }
2644 }
2645
2646 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2647 # Real waits are implemented in the subclass.
2648 return 0;
2649 }
2650
2651 public function getSlavePos() {
2652 # Stub
2653 return false;
2654 }
2655
2656 public function getMasterPos() {
2657 # Stub
2658 return false;
2659 }
2660
2661 public function serverIsReadOnly() {
2662 return false;
2663 }
2664
2665 final public function onTransactionResolution( callable $callback ) {
2666 if ( !$this->mTrxLevel ) {
2667 throw new DBUnexpectedError( $this, "No transaction is active." );
2668 }
2669 $this->mTrxEndCallbacks[] = [ $callback, wfGetCaller() ];
2670 }
2671
2672 final public function onTransactionIdle( callable $callback ) {
2673 $this->mTrxIdleCallbacks[] = [ $callback, wfGetCaller() ];
2674 if ( !$this->mTrxLevel ) {
2675 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2676 }
2677 }
2678
2679 final public function onTransactionPreCommitOrIdle( callable $callback ) {
2680 if ( $this->mTrxLevel ) {
2681 $this->mTrxPreCommitCallbacks[] = [ $callback, wfGetCaller() ];
2682 } else {
2683 // If no transaction is active, then make one for this callback
2684 $this->startAtomic( __METHOD__ );
2685 try {
2686 call_user_func( $callback );
2687 $this->endAtomic( __METHOD__ );
2688 } catch ( Exception $e ) {
2689 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2690 throw $e;
2691 }
2692 }
2693 }
2694
2695 final public function setTransactionListener( $name, callable $callback = null ) {
2696 if ( $callback ) {
2697 $this->mTrxRecurringCallbacks[$name] = [ $callback, wfGetCaller() ];
2698 } else {
2699 unset( $this->mTrxRecurringCallbacks[$name] );
2700 }
2701 }
2702
2703 /**
2704 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2705 *
2706 * This method should not be used outside of Database/LoadBalancer
2707 *
2708 * @param bool $suppress
2709 * @since 1.28
2710 */
2711 final public function setTrxEndCallbackSuppression( $suppress ) {
2712 $this->mTrxEndCallbacksSuppressed = $suppress;
2713 }
2714
2715 /**
2716 * Actually run and consume any "on transaction idle/resolution" callbacks.
2717 *
2718 * This method should not be used outside of Database/LoadBalancer
2719 *
2720 * @param integer $trigger IDatabase::TRIGGER_* constant
2721 * @since 1.20
2722 * @throws Exception
2723 */
2724 public function runOnTransactionIdleCallbacks( $trigger ) {
2725 if ( $this->mTrxEndCallbacksSuppressed ) {
2726 return;
2727 }
2728
2729 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2730 /** @var Exception $e */
2731 $e = null; // first exception
2732 do { // callbacks may add callbacks :)
2733 $callbacks = array_merge(
2734 $this->mTrxIdleCallbacks,
2735 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2736 );
2737 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2738 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2739 foreach ( $callbacks as $callback ) {
2740 try {
2741 list( $phpCallback ) = $callback;
2742 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2743 call_user_func_array( $phpCallback, [ $trigger ] );
2744 if ( $autoTrx ) {
2745 $this->setFlag( DBO_TRX ); // restore automatic begin()
2746 } else {
2747 $this->clearFlag( DBO_TRX ); // restore auto-commit
2748 }
2749 } catch ( Exception $ex ) {
2750 call_user_func( $this->errorLogger, $ex );
2751 $e = $e ?: $ex;
2752 // Some callbacks may use startAtomic/endAtomic, so make sure
2753 // their transactions are ended so other callbacks don't fail
2754 if ( $this->trxLevel() ) {
2755 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2756 }
2757 }
2758 }
2759 } while ( count( $this->mTrxIdleCallbacks ) );
2760
2761 if ( $e instanceof Exception ) {
2762 throw $e; // re-throw any first exception
2763 }
2764 }
2765
2766 /**
2767 * Actually run and consume any "on transaction pre-commit" callbacks.
2768 *
2769 * This method should not be used outside of Database/LoadBalancer
2770 *
2771 * @since 1.22
2772 * @throws Exception
2773 */
2774 public function runOnTransactionPreCommitCallbacks() {
2775 $e = null; // first exception
2776 do { // callbacks may add callbacks :)
2777 $callbacks = $this->mTrxPreCommitCallbacks;
2778 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2779 foreach ( $callbacks as $callback ) {
2780 try {
2781 list( $phpCallback ) = $callback;
2782 call_user_func( $phpCallback );
2783 } catch ( Exception $ex ) {
2784 call_user_func( $this->errorLogger, $ex );
2785 $e = $e ?: $ex;
2786 }
2787 }
2788 } while ( count( $this->mTrxPreCommitCallbacks ) );
2789
2790 if ( $e instanceof Exception ) {
2791 throw $e; // re-throw any first exception
2792 }
2793 }
2794
2795 /**
2796 * Actually run any "transaction listener" callbacks.
2797 *
2798 * This method should not be used outside of Database/LoadBalancer
2799 *
2800 * @param integer $trigger IDatabase::TRIGGER_* constant
2801 * @throws Exception
2802 * @since 1.20
2803 */
2804 public function runTransactionListenerCallbacks( $trigger ) {
2805 if ( $this->mTrxEndCallbacksSuppressed ) {
2806 return;
2807 }
2808
2809 /** @var Exception $e */
2810 $e = null; // first exception
2811
2812 foreach ( $this->mTrxRecurringCallbacks as $callback ) {
2813 try {
2814 list( $phpCallback ) = $callback;
2815 $phpCallback( $trigger, $this );
2816 } catch ( Exception $ex ) {
2817 call_user_func( $this->errorLogger, $ex );
2818 $e = $e ?: $ex;
2819 }
2820 }
2821
2822 if ( $e instanceof Exception ) {
2823 throw $e; // re-throw any first exception
2824 }
2825 }
2826
2827 final public function startAtomic( $fname = __METHOD__ ) {
2828 if ( !$this->mTrxLevel ) {
2829 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2830 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2831 // in all changes being in one transaction to keep requests transactional.
2832 if ( !$this->getFlag( DBO_TRX ) ) {
2833 $this->mTrxAutomaticAtomic = true;
2834 }
2835 }
2836
2837 $this->mTrxAtomicLevels[] = $fname;
2838 }
2839
2840 final public function endAtomic( $fname = __METHOD__ ) {
2841 if ( !$this->mTrxLevel ) {
2842 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2843 }
2844 if ( !$this->mTrxAtomicLevels ||
2845 array_pop( $this->mTrxAtomicLevels ) !== $fname
2846 ) {
2847 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2848 }
2849
2850 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2851 $this->commit( $fname, self::FLUSHING_INTERNAL );
2852 }
2853 }
2854
2855 final public function doAtomicSection( $fname, callable $callback ) {
2856 $this->startAtomic( $fname );
2857 try {
2858 $res = call_user_func_array( $callback, [ $this, $fname ] );
2859 } catch ( Exception $e ) {
2860 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2861 throw $e;
2862 }
2863 $this->endAtomic( $fname );
2864
2865 return $res;
2866 }
2867
2868 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2869 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2870 if ( $this->mTrxLevel ) {
2871 if ( $this->mTrxAtomicLevels ) {
2872 $levels = implode( ', ', $this->mTrxAtomicLevels );
2873 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2874 throw new DBUnexpectedError( $this, $msg );
2875 } elseif ( !$this->mTrxAutomatic ) {
2876 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2877 throw new DBUnexpectedError( $this, $msg );
2878 } else {
2879 // @TODO: make this an exception at some point
2880 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2881 $this->queryLogger->error( $msg );
2882 return; // join the main transaction set
2883 }
2884 } elseif ( $this->getFlag( DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2885 // @TODO: make this an exception at some point
2886 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2887 $this->queryLogger->error( $msg );
2888 return; // let any writes be in the main transaction
2889 }
2890
2891 // Avoid fatals if close() was called
2892 $this->assertOpen();
2893
2894 $this->doBegin( $fname );
2895 $this->mTrxTimestamp = microtime( true );
2896 $this->mTrxFname = $fname;
2897 $this->mTrxDoneWrites = false;
2898 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2899 $this->mTrxAutomaticAtomic = false;
2900 $this->mTrxAtomicLevels = [];
2901 $this->mTrxShortId = wfRandomString( 12 );
2902 $this->mTrxWriteDuration = 0.0;
2903 $this->mTrxWriteQueryCount = 0;
2904 $this->mTrxWriteAdjDuration = 0.0;
2905 $this->mTrxWriteAdjQueryCount = 0;
2906 $this->mTrxWriteCallers = [];
2907 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2908 // Get an estimate of the replica DB lag before then, treating estimate staleness
2909 // as lag itself just to be safe
2910 $status = $this->getApproximateLagStatus();
2911 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2912 }
2913
2914 /**
2915 * Issues the BEGIN command to the database server.
2916 *
2917 * @see DatabaseBase::begin()
2918 * @param string $fname
2919 */
2920 protected function doBegin( $fname ) {
2921 $this->query( 'BEGIN', $fname );
2922 $this->mTrxLevel = 1;
2923 }
2924
2925 final public function commit( $fname = __METHOD__, $flush = '' ) {
2926 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2927 // There are still atomic sections open. This cannot be ignored
2928 $levels = implode( ', ', $this->mTrxAtomicLevels );
2929 throw new DBUnexpectedError(
2930 $this,
2931 "$fname: Got COMMIT while atomic sections $levels are still open."
2932 );
2933 }
2934
2935 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2936 if ( !$this->mTrxLevel ) {
2937 return; // nothing to do
2938 } elseif ( !$this->mTrxAutomatic ) {
2939 throw new DBUnexpectedError(
2940 $this,
2941 "$fname: Flushing an explicit transaction, getting out of sync."
2942 );
2943 }
2944 } else {
2945 if ( !$this->mTrxLevel ) {
2946 $this->queryLogger->error( "$fname: No transaction to commit, something got out of sync." );
2947 return; // nothing to do
2948 } elseif ( $this->mTrxAutomatic ) {
2949 // @TODO: make this an exception at some point
2950 $msg = "$fname: Explicit commit of implicit transaction.";
2951 $this->queryLogger->error( $msg );
2952 return; // wait for the main transaction set commit round
2953 }
2954 }
2955
2956 // Avoid fatals if close() was called
2957 $this->assertOpen();
2958
2959 $this->runOnTransactionPreCommitCallbacks();
2960 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2961 $this->doCommit( $fname );
2962 if ( $this->mTrxDoneWrites ) {
2963 $this->mDoneWrites = microtime( true );
2964 $this->trxProfiler->transactionWritingOut(
2965 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2966 }
2967
2968 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2969 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2970 }
2971
2972 /**
2973 * Issues the COMMIT command to the database server.
2974 *
2975 * @see DatabaseBase::commit()
2976 * @param string $fname
2977 */
2978 protected function doCommit( $fname ) {
2979 if ( $this->mTrxLevel ) {
2980 $this->query( 'COMMIT', $fname );
2981 $this->mTrxLevel = 0;
2982 }
2983 }
2984
2985 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2986 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2987 if ( !$this->mTrxLevel ) {
2988 return; // nothing to do
2989 }
2990 } else {
2991 if ( !$this->mTrxLevel ) {
2992 $this->queryLogger->error(
2993 "$fname: No transaction to rollback, something got out of sync." );
2994 return; // nothing to do
2995 } elseif ( $this->getFlag( DBO_TRX ) ) {
2996 throw new DBUnexpectedError(
2997 $this,
2998 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2999 );
3000 }
3001 }
3002
3003 // Avoid fatals if close() was called
3004 $this->assertOpen();
3005
3006 $this->doRollback( $fname );
3007 $this->mTrxAtomicLevels = [];
3008 if ( $this->mTrxDoneWrites ) {
3009 $this->trxProfiler->transactionWritingOut(
3010 $this->mServer, $this->mDBname, $this->mTrxShortId );
3011 }
3012
3013 $this->mTrxIdleCallbacks = []; // clear
3014 $this->mTrxPreCommitCallbacks = []; // clear
3015 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3016 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3017 }
3018
3019 /**
3020 * Issues the ROLLBACK command to the database server.
3021 *
3022 * @see DatabaseBase::rollback()
3023 * @param string $fname
3024 */
3025 protected function doRollback( $fname ) {
3026 if ( $this->mTrxLevel ) {
3027 # Disconnects cause rollback anyway, so ignore those errors
3028 $ignoreErrors = true;
3029 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3030 $this->mTrxLevel = 0;
3031 }
3032 }
3033
3034 public function flushSnapshot( $fname = __METHOD__ ) {
3035 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3036 // This only flushes transactions to clear snapshots, not to write data
3037 throw new DBUnexpectedError(
3038 $this,
3039 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3040 );
3041 }
3042
3043 $this->commit( $fname, self::FLUSHING_INTERNAL );
3044 }
3045
3046 public function explicitTrxActive() {
3047 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
3048 }
3049
3050 /**
3051 * Creates a new table with structure copied from existing table
3052 * Note that unlike most database abstraction functions, this function does not
3053 * automatically append database prefix, because it works at a lower
3054 * abstraction level.
3055 * The table names passed to this function shall not be quoted (this
3056 * function calls addIdentifierQuotes when needed).
3057 *
3058 * @param string $oldName Name of table whose structure should be copied
3059 * @param string $newName Name of table to be created
3060 * @param bool $temporary Whether the new table should be temporary
3061 * @param string $fname Calling function name
3062 * @throws RuntimeException
3063 * @return bool True if operation was successful
3064 */
3065 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3066 $fname = __METHOD__
3067 ) {
3068 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3069 }
3070
3071 function listTables( $prefix = null, $fname = __METHOD__ ) {
3072 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3073 }
3074
3075 /**
3076 * Reset the views process cache set by listViews()
3077 * @since 1.22
3078 */
3079 final public function clearViewsCache() {
3080 $this->allViews = null;
3081 }
3082
3083 /**
3084 * Lists all the VIEWs in the database
3085 *
3086 * For caching purposes the list of all views should be stored in
3087 * $this->allViews. The process cache can be cleared with clearViewsCache()
3088 *
3089 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3090 * @param string $fname Name of calling function
3091 * @throws RuntimeException
3092 * @return array
3093 * @since 1.22
3094 */
3095 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3096 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3097 }
3098
3099 /**
3100 * Differentiates between a TABLE and a VIEW
3101 *
3102 * @param string $name Name of the database-structure to test.
3103 * @throws RuntimeException
3104 * @return bool
3105 * @since 1.22
3106 */
3107 public function isView( $name ) {
3108 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3109 }
3110
3111 public function timestamp( $ts = 0 ) {
3112 return wfTimestamp( TS_MW, $ts );
3113 }
3114
3115 public function timestampOrNull( $ts = null ) {
3116 if ( is_null( $ts ) ) {
3117 return null;
3118 } else {
3119 return $this->timestamp( $ts );
3120 }
3121 }
3122
3123 /**
3124 * Take the result from a query, and wrap it in a ResultWrapper if
3125 * necessary. Boolean values are passed through as is, to indicate success
3126 * of write queries or failure.
3127 *
3128 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3129 * resource, and it was necessary to call this function to convert it to
3130 * a wrapper. Nowadays, raw database objects are never exposed to external
3131 * callers, so this is unnecessary in external code.
3132 *
3133 * @param bool|ResultWrapper|resource|object $result
3134 * @return bool|ResultWrapper
3135 */
3136 protected function resultObject( $result ) {
3137 if ( !$result ) {
3138 return false;
3139 } elseif ( $result instanceof ResultWrapper ) {
3140 return $result;
3141 } elseif ( $result === true ) {
3142 // Successful write query
3143 return $result;
3144 } else {
3145 return new ResultWrapper( $this, $result );
3146 }
3147 }
3148
3149 public function ping( &$rtt = null ) {
3150 // Avoid hitting the server if it was hit recently
3151 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3152 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
3153 $rtt = $this->mRTTEstimate;
3154 return true; // don't care about $rtt
3155 }
3156 }
3157
3158 // This will reconnect if possible or return false if not
3159 $this->clearFlag( DBO_TRX, self::REMEMBER_PRIOR );
3160 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3161 $this->restoreFlags( self::RESTORE_PRIOR );
3162
3163 if ( $ok ) {
3164 $rtt = $this->mRTTEstimate;
3165 }
3166
3167 return $ok;
3168 }
3169
3170 /**
3171 * @return bool
3172 */
3173 protected function reconnect() {
3174 $this->closeConnection();
3175 $this->mOpened = false;
3176 $this->mConn = false;
3177 try {
3178 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3179 $this->lastPing = microtime( true );
3180 $ok = true;
3181 } catch ( DBConnectionError $e ) {
3182 $ok = false;
3183 }
3184
3185 return $ok;
3186 }
3187
3188 public function getSessionLagStatus() {
3189 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3190 }
3191
3192 /**
3193 * Get the replica DB lag when the current transaction started
3194 *
3195 * This is useful when transactions might use snapshot isolation
3196 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3197 * is this lag plus transaction duration. If they don't, it is still
3198 * safe to be pessimistic. This returns null if there is no transaction.
3199 *
3200 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3201 * @since 1.27
3202 */
3203 public function getTransactionLagStatus() {
3204 return $this->mTrxLevel
3205 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3206 : null;
3207 }
3208
3209 /**
3210 * Get a replica DB lag estimate for this server
3211 *
3212 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3213 * @since 1.27
3214 */
3215 public function getApproximateLagStatus() {
3216 return [
3217 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3218 'since' => microtime( true )
3219 ];
3220 }
3221
3222 /**
3223 * Merge the result of getSessionLagStatus() for several DBs
3224 * using the most pessimistic values to estimate the lag of
3225 * any data derived from them in combination
3226 *
3227 * This is information is useful for caching modules
3228 *
3229 * @see WANObjectCache::set()
3230 * @see WANObjectCache::getWithSetCallback()
3231 *
3232 * @param IDatabase $db1
3233 * @param IDatabase ...
3234 * @return array Map of values:
3235 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3236 * - since: oldest UNIX timestamp of any of the DB lag estimates
3237 * - pending: whether any of the DBs have uncommitted changes
3238 * @since 1.27
3239 */
3240 public static function getCacheSetOptions( IDatabase $db1 ) {
3241 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3242 foreach ( func_get_args() as $db ) {
3243 /** @var IDatabase $db */
3244 $status = $db->getSessionLagStatus();
3245 if ( $status['lag'] === false ) {
3246 $res['lag'] = false;
3247 } elseif ( $res['lag'] !== false ) {
3248 $res['lag'] = max( $res['lag'], $status['lag'] );
3249 }
3250 $res['since'] = min( $res['since'], $status['since'] );
3251 $res['pending'] = $res['pending'] ?: $db->writesPending();
3252 }
3253
3254 return $res;
3255 }
3256
3257 public function getLag() {
3258 return 0;
3259 }
3260
3261 function maxListLen() {
3262 return 0;
3263 }
3264
3265 public function encodeBlob( $b ) {
3266 return $b;
3267 }
3268
3269 public function decodeBlob( $b ) {
3270 if ( $b instanceof Blob ) {
3271 $b = $b->fetch();
3272 }
3273 return $b;
3274 }
3275
3276 public function setSessionOptions( array $options ) {
3277 }
3278
3279 /**
3280 * Read and execute SQL commands from a file.
3281 *
3282 * Returns true on success, error string or exception on failure (depending
3283 * on object's error ignore settings).
3284 *
3285 * @param string $filename File name to open
3286 * @param bool|callable $lineCallback Optional function called before reading each line
3287 * @param bool|callable $resultCallback Optional function called for each MySQL result
3288 * @param bool|string $fname Calling function name or false if name should be
3289 * generated dynamically using $filename
3290 * @param bool|callable $inputCallback Optional function called for each
3291 * complete line sent
3292 * @return bool|string
3293 * @throws Exception
3294 */
3295 public function sourceFile(
3296 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3297 ) {
3298 MediaWiki\suppressWarnings();
3299 $fp = fopen( $filename, 'r' );
3300 MediaWiki\restoreWarnings();
3301
3302 if ( false === $fp ) {
3303 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3304 }
3305
3306 if ( !$fname ) {
3307 $fname = __METHOD__ . "( $filename )";
3308 }
3309
3310 try {
3311 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3312 } catch ( Exception $e ) {
3313 fclose( $fp );
3314 throw $e;
3315 }
3316
3317 fclose( $fp );
3318
3319 return $error;
3320 }
3321
3322 public function setSchemaVars( $vars ) {
3323 $this->mSchemaVars = $vars;
3324 }
3325
3326 /**
3327 * Read and execute commands from an open file handle.
3328 *
3329 * Returns true on success, error string or exception on failure (depending
3330 * on object's error ignore settings).
3331 *
3332 * @param resource $fp File handle
3333 * @param bool|callable $lineCallback Optional function called before reading each query
3334 * @param bool|callable $resultCallback Optional function called for each MySQL result
3335 * @param string $fname Calling function name
3336 * @param bool|callable $inputCallback Optional function called for each complete query sent
3337 * @return bool|string
3338 */
3339 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3340 $fname = __METHOD__, $inputCallback = false
3341 ) {
3342 $cmd = '';
3343
3344 while ( !feof( $fp ) ) {
3345 if ( $lineCallback ) {
3346 call_user_func( $lineCallback );
3347 }
3348
3349 $line = trim( fgets( $fp ) );
3350
3351 if ( $line == '' ) {
3352 continue;
3353 }
3354
3355 if ( '-' == $line[0] && '-' == $line[1] ) {
3356 continue;
3357 }
3358
3359 if ( $cmd != '' ) {
3360 $cmd .= ' ';
3361 }
3362
3363 $done = $this->streamStatementEnd( $cmd, $line );
3364
3365 $cmd .= "$line\n";
3366
3367 if ( $done || feof( $fp ) ) {
3368 $cmd = $this->replaceVars( $cmd );
3369
3370 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3371 $res = $this->query( $cmd, $fname );
3372
3373 if ( $resultCallback ) {
3374 call_user_func( $resultCallback, $res, $this );
3375 }
3376
3377 if ( false === $res ) {
3378 $err = $this->lastError();
3379
3380 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3381 }
3382 }
3383 $cmd = '';
3384 }
3385 }
3386
3387 return true;
3388 }
3389
3390 /**
3391 * Called by sourceStream() to check if we've reached a statement end
3392 *
3393 * @param string $sql SQL assembled so far
3394 * @param string $newLine New line about to be added to $sql
3395 * @return bool Whether $newLine contains end of the statement
3396 */
3397 public function streamStatementEnd( &$sql, &$newLine ) {
3398 if ( $this->delimiter ) {
3399 $prev = $newLine;
3400 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3401 if ( $newLine != $prev ) {
3402 return true;
3403 }
3404 }
3405
3406 return false;
3407 }
3408
3409 /**
3410 * Database independent variable replacement. Replaces a set of variables
3411 * in an SQL statement with their contents as given by $this->getSchemaVars().
3412 *
3413 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3414 *
3415 * - '{$var}' should be used for text and is passed through the database's
3416 * addQuotes method.
3417 * - `{$var}` should be used for identifiers (e.g. table and database names).
3418 * It is passed through the database's addIdentifierQuotes method which
3419 * can be overridden if the database uses something other than backticks.
3420 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3421 * database's tableName method.
3422 * - / *i* / passes the name that follows through the database's indexName method.
3423 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3424 * its use should be avoided. In 1.24 and older, string encoding was applied.
3425 *
3426 * @param string $ins SQL statement to replace variables in
3427 * @return string The new SQL statement with variables replaced
3428 */
3429 protected function replaceVars( $ins ) {
3430 $vars = $this->getSchemaVars();
3431 return preg_replace_callback(
3432 '!
3433 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3434 \'\{\$ (\w+) }\' | # 3. addQuotes
3435 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3436 /\*\$ (\w+) \*/ # 5. leave unencoded
3437 !x',
3438 function ( $m ) use ( $vars ) {
3439 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3440 // check for both nonexistent keys *and* the empty string.
3441 if ( isset( $m[1] ) && $m[1] !== '' ) {
3442 if ( $m[1] === 'i' ) {
3443 return $this->indexName( $m[2] );
3444 } else {
3445 return $this->tableName( $m[2] );
3446 }
3447 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3448 return $this->addQuotes( $vars[$m[3]] );
3449 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3450 return $this->addIdentifierQuotes( $vars[$m[4]] );
3451 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3452 return $vars[$m[5]];
3453 } else {
3454 return $m[0];
3455 }
3456 },
3457 $ins
3458 );
3459 }
3460
3461 /**
3462 * Get schema variables. If none have been set via setSchemaVars(), then
3463 * use some defaults from the current object.
3464 *
3465 * @return array
3466 */
3467 protected function getSchemaVars() {
3468 if ( $this->mSchemaVars ) {
3469 return $this->mSchemaVars;
3470 } else {
3471 return $this->getDefaultSchemaVars();
3472 }
3473 }
3474
3475 /**
3476 * Get schema variables to use if none have been set via setSchemaVars().
3477 *
3478 * Override this in derived classes to provide variables for tables.sql
3479 * and SQL patch files.
3480 *
3481 * @return array
3482 */
3483 protected function getDefaultSchemaVars() {
3484 return [];
3485 }
3486
3487 public function lockIsFree( $lockName, $method ) {
3488 return true;
3489 }
3490
3491 public function lock( $lockName, $method, $timeout = 5 ) {
3492 $this->mNamedLocksHeld[$lockName] = 1;
3493
3494 return true;
3495 }
3496
3497 public function unlock( $lockName, $method ) {
3498 unset( $this->mNamedLocksHeld[$lockName] );
3499
3500 return true;
3501 }
3502
3503 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3504 if ( $this->writesOrCallbacksPending() ) {
3505 // This only flushes transactions to clear snapshots, not to write data
3506 throw new DBUnexpectedError(
3507 $this,
3508 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3509 );
3510 }
3511
3512 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3513 return null;
3514 }
3515
3516 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3517 if ( $this->trxLevel() ) {
3518 // There is a good chance an exception was thrown, causing any early return
3519 // from the caller. Let any error handler get a chance to issue rollback().
3520 // If there isn't one, let the error bubble up and trigger server-side rollback.
3521 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3522 $this->unlock( $lockKey, $fname );
3523 } );
3524 } else {
3525 $this->unlock( $lockKey, $fname );
3526 }
3527 } );
3528
3529 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
3530
3531 return $unlocker;
3532 }
3533
3534 public function namedLocksEnqueue() {
3535 return false;
3536 }
3537
3538 /**
3539 * Lock specific tables
3540 *
3541 * @param array $read Array of tables to lock for read access
3542 * @param array $write Array of tables to lock for write access
3543 * @param string $method Name of caller
3544 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3545 * @return bool
3546 */
3547 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3548 return true;
3549 }
3550
3551 /**
3552 * Unlock specific tables
3553 *
3554 * @param string $method The caller
3555 * @return bool
3556 */
3557 public function unlockTables( $method ) {
3558 return true;
3559 }
3560
3561 /**
3562 * Delete a table
3563 * @param string $tableName
3564 * @param string $fName
3565 * @return bool|ResultWrapper
3566 * @since 1.18
3567 */
3568 public function dropTable( $tableName, $fName = __METHOD__ ) {
3569 if ( !$this->tableExists( $tableName, $fName ) ) {
3570 return false;
3571 }
3572 $sql = "DROP TABLE " . $this->tableName( $tableName );
3573 if ( $this->cascadingDeletes() ) {
3574 $sql .= " CASCADE";
3575 }
3576
3577 return $this->query( $sql, $fName );
3578 }
3579
3580 /**
3581 * Get search engine class. All subclasses of this need to implement this
3582 * if they wish to use searching.
3583 *
3584 * @return string
3585 */
3586 public function getSearchEngine() {
3587 return 'SearchEngineDummy';
3588 }
3589
3590 public function getInfinity() {
3591 return 'infinity';
3592 }
3593
3594 public function encodeExpiry( $expiry ) {
3595 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3596 ? $this->getInfinity()
3597 : $this->timestamp( $expiry );
3598 }
3599
3600 public function decodeExpiry( $expiry, $format = TS_MW ) {
3601 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3602 ? 'infinity'
3603 : wfTimestamp( $format, $expiry );
3604 }
3605
3606 public function setBigSelects( $value = true ) {
3607 // no-op
3608 }
3609
3610 public function isReadOnly() {
3611 return ( $this->getReadOnlyReason() !== false );
3612 }
3613
3614 /**
3615 * @return string|bool Reason this DB is read-only or false if it is not
3616 */
3617 protected function getReadOnlyReason() {
3618 $reason = $this->getLBInfo( 'readOnlyReason' );
3619
3620 return is_string( $reason ) ? $reason : false;
3621 }
3622
3623 public function setTableAliases( array $aliases ) {
3624 $this->tableAliases = $aliases;
3625 }
3626
3627 /**
3628 * @since 1.19
3629 * @return string
3630 */
3631 public function __toString() {
3632 return (string)$this->mConn;
3633 }
3634
3635 /**
3636 * Run a few simple sanity checks
3637 */
3638 public function __destruct() {
3639 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3640 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3641 }
3642 $danglingCallbacks = array_merge(
3643 $this->mTrxIdleCallbacks,
3644 $this->mTrxPreCommitCallbacks,
3645 $this->mTrxEndCallbacks
3646 );
3647 if ( $danglingCallbacks ) {
3648 $callers = [];
3649 foreach ( $danglingCallbacks as $callbackInfo ) {
3650 $callers[] = $callbackInfo[1];
3651 }
3652 $callers = implode( ', ', $callers );
3653 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3654 }
3655 }
3656 }
3657
3658 /**
3659 * @since 1.27
3660 */
3661 abstract class Database extends DatabaseBase {
3662 // B/C until nothing type hints for DatabaseBase
3663 // @TODO: finish renaming DatabaseBase => Database
3664 }